
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using SqlSugar;
using System.Collections.Generic;
using System.Linq.Expressions;
using Util;

namespace API.Controllers
{
    public class CanteenClientController : BaseController
    {
        Repository<tCanteenClient> _CanteenClient;
        Repository<tFile> _File;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        public CanteenClientController(Repository<tCanteenClient> CanteenClient, IMapper mapper, ISqlSugarClient db, Repository<tFile> file)
        {
            _CanteenClient = CanteenClient;
            _mapper = mapper;
            _db = db;
            _File = file;
        }
        /// <summary>
        /// 保存版面数据
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> SaveData([FromBody] SaveCanteenClientInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tCanteenClient>(dto);
                InitEntity(model);
                await _CanteenClient.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenClientController--SaveData:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 分页获取版面
        /// </summary>
        /// <param name="inx"></param>
        /// <param name="row"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<CanteenClientOutput>>> GetClient(CanteenClientListInput dto)
        {
            ResultMsg<List<CanteenClientOutput>> result = new ResultMsg<List<CanteenClientOutput>>();
            try
            {
                Expressionable<tCanteenClient, tCanteenPlan> expressionable = Expressionable.Create<tCanteenClient, tCanteenPlan>();//实例化Expressionable
                expressionable.AndIF(dto.search != "$", (client, plans) => client.FName.Contains(dto.search));//添加条件
                Expression<Func<tCanteenClient, tCanteenPlan, bool>> expression = expressionable.ToExpression();//将Expressionable转为Expression

                int totalCount = 0;
                int totalPage = 0;
                var lst = await Task.Run(() => _db.Queryable<tCanteenClient, tCanteenPlan>((client, plans) => new JoinQueryInfos(
                    JoinType.Left, client.FPlanID.Equals(plans.Id)
                    )).Where(expression).OrderBy((client, plans) => client.CreateTime, OrderByType.Desc).Select((client, plans) => new CanteenClientOutput
                    {
                       Id= client.Id,
                       Name= client.FName,
                       PlanID= client.FPlanID,
                       ChageDate= client.FChageDate,
                       Code= client.FCode,
                        PlanName = plans.FName,
                        FShowType = plans.FShowType,
                       Remark=  client.FRemark
                    }).ToPageList(dto.PageNum, dto.PageSize, ref totalCount, ref totalPage));
                return result.Success(lst, totalPage);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenClientController--GetClient:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 设置方案
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="planID"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> ChangeClientPlan(ChangeClientPlanInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var client = await _CanteenClient.GetByIdAsync(dto.clientID);
                if (client == null)
                    return result.Error("找不到该版面");
                client.FPlanID = dto.planID;
                bool b = await _CanteenClient.UpdateAsync(client);
                if (b)
                    return result.Success();
                return result.Error();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenClientController--ChangePlan:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取版面展示文件
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<CanteenPlanOutput>> GetPlanFileByCodes(string code)
        {
            ResultMsg<CanteenPlanOutput> result= new ResultMsg<CanteenPlanOutput>();
            try
            {
                var client = await _CanteenClient.GetSingleAsync(t => t.FCode.Equals(code));
                var planID = client.FPlanID;
                var entity = _db.Queryable<tCanteenPlan>().InSingle(planID);
                CanteenPlanOutput planOutput=_mapper.Map<CanteenPlanOutput>(entity);
                if (entity != null)
                {
                    var files = await _File.GetListAsync(t => t.FPlanID.Equals(planID) && t.FShowType.Equals(entity.FShowType));

                    planOutput.Filelst =_mapper.Map<List<FileOutput>>(files);
                }
                return result.Success(planOutput);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenClientController--GetFileByCode:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 删除版面
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> DelClient([FromBody] object[] ids)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                bool b = await _CanteenClient.DeleteByIdsAsync(ids);
                if (b)
                    return result.Success();
                return result.Error();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenClientController--DelClient:" + ex.ToString());
                return result.Exception();
            }
        }
    }
}
